package com.yym.ssh;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

public class MutipleCommand {

	private static String host = "192.168.198.143";
	private static String username = "root";
	private static String password = "1";
	private Connection conn = null;

	public MutipleCommand(String host, String username, String password) {
		super();
		this.host = host;
		this.username = username;
		this.password = password;

		conn = new Connection(host);

		try {
			conn.connect();
			System.out.println("ok");
			boolean isAuthentied = conn.authenticateWithPassword(username,
					password);
			if (!isAuthentied) {

				System.out.println("Authenticated failed...");
			}

		} catch (IOException e) {
			System.err.println("error");
		}

	}

	public void testOpt() {
		try {
			Session sess = conn.openSession();
			// sess.execCommand("ls -l");
			
			
			
			sess.requestPTY("bash");
			sess.startShell();

			BufferedReader stdoutReader = new BufferedReader(
					new InputStreamReader(sess.getStdout()));
			BufferedReader stderrReader = new BufferedReader(
					new InputStreamReader(sess.getStderr()));
			// InputStream err = sess.getStderr();
			// OutputStream out = sess.getStdin();

			PrintWriter print = new PrintWriter(sess.getStdin());
			print.print("env");

			// print.flush();
			print.print("ls");
			// print.flush();

			print.close();

			// sess.waitForCondition(ChannelCondition.CLOSED
			// | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,
			// 30000);

			System.out.println("###############output###################");
			while (true) {
				String line = stdoutReader.readLine();
				if (line == null)
					break;
				System.out.println(line);
			}

//			while (true) {
//				String line = stderrReader.readLine();
//				if (line == null)
//					break;
//				System.out.println(line);
//
//			}
		} catch (IOException e) {
			System.out.println("open session error");
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		new MutipleCommand(host, username, password).testOpt();
	}

}
